package com.seu.dm.controllers;

import com.github.pagehelper.PageHelper;
import com.seu.dm.annotations.permissions.BuyerPermission;
import com.seu.dm.dto.SeckillEntryDTO;
import com.seu.dm.dto.UserBaseDTO;
import com.seu.dm.entities.Product;
import com.seu.dm.entities.Seckill;
import com.seu.dm.helpers.RedisHelper;
import com.seu.dm.services.ProductService;
import com.seu.dm.services.SeckillService;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import sun.java2d.pipe.SpanShapeRenderer;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Greeting on 2017/3/20.
 */
@Controller
@RequestMapping(value="/seckill")
public class SeckillController {
    @Autowired
    private SeckillService seckillService;
    @Autowired
    private ProductService productService;


    @RequestMapping(value="/mytest")
    @ResponseBody
    public String mytest(HttpSession httpSession){

        Jedis jedis = RedisHelper.getJedis();
        jedis.del("seckillSet:1");
        return "";
    }

    @RequestMapping(value="/doadd/")
    public String doAdd(@RequestParam Integer id, @RequestParam Integer number,
                        @RequestParam String startTime,
                        Model model)throws ParseException{
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = format.parse(startTime);
        Product product = productService.findProduct(id);
        if(number <= 0){
            model.addAttribute("message","请填写正确的数量");
            model.addAttribute("jumpUrl","/register");
            return "common/alert";
        }
        BigDecimal price = new BigDecimal(0);
        if(product.getInventory() < number){
            model.addAttribute("message","库存数量不够");
            model.addAttribute("jumpUrl","/register");
            return "common/alert";
        }
        product.setInventory(product.getInventory()-number);
        Seckill seckill = new Seckill();
        seckill.setNumber(number);
        seckill.setKillPrice(price);
        seckill.setStartTime(date);
        seckill.setProductId(product.getId());
        seckillService.publishSeckill(seckill,product);
        return "redirect:/seller/stock";
    }


    /**
     * 列表页
     * @return
     */
    @RequestMapping("/")
    public String index(Model model){
        long startTime = new Date().getTime() + 24*60*60*1000;
        List<Seckill> seckillList = seckillService.queryAllStandByByStartTimeWithProduct(new Date(startTime));
        model.addAttribute("list",seckillList);
        return "secKill/secKillList";
    }

    /**
     * 详情页
     * @return
     */
    @RequestMapping("/detail/{id}")
    @BuyerPermission
    public String detail(@PathVariable long id, Model model){
        Seckill seckill = seckillService.getSeckillById(id);
        model.addAttribute("one",seckill);
        return "secKill/secKillDetail";
    }

    /**
     * 获取秒杀入口
     * @return
     */
    @RequestMapping("/getkillentry/{id}")
    @ResponseBody
    public SeckillEntryDTO getKillEntry(@PathVariable long id){
        SeckillEntryDTO seckillEntry = seckillService.getSeckillEntry(id);
        return seckillEntry;
    }

    /**
     * 执行秒杀
     * @return
     */
    @RequestMapping("/dokill/{id}/{md5}")
    @BuyerPermission
    public String doKill(@PathVariable long id,@PathVariable String md5,HttpSession httpSession,Model model){
        SeckillEntryDTO seckillEntry =  seckillService.getSeckillEntry(id);
        if(seckillEntry == null){
            model.addAttribute("message","非法请求");
            model.addAttribute("jumpUrl","/");
            return "common/alert";
        }
        if(!seckillEntry.getMd5().equals(md5)){
            model.addAttribute("message","非法请求");
            model.addAttribute("jumpUrl","/");
            return "common/alert";
        }
        UserBaseDTO userBase = (UserBaseDTO)httpSession.getAttribute("userBase");
        int result = seckillService.executeSeckill(id,userBase.getId());
        System.out.println("finish transaction");
        if(result == 0){
            model.addAttribute("message","已经抢完");
            model.addAttribute("jumpUrl","/");
        }else if(result == 2){
            model.addAttribute("message","不能重复抢购");
            model.addAttribute("jumpUrl","/buyer/orders");
        }else if(result == 1){
            model.addAttribute("message","抢购成功");
            model.addAttribute("jumpUrl","/buyer/orders");

        }

        return "common/alert";

    }


}
